<template>
  <div style="display:flex;"
       :class="{ 'imgCenter' : !text }">
    <div v-if="!showCroper">

      <div v-if="!text">
        <img @click="selectFile"
             :style="{width: iconWidth + 'px', height: iconHeight + 'px'}"
             src="https://ssl-oss.raiseinfo.cn/uploadimage.png" />
        <input type="file"
               accept="image/*"
               :id="id"
               @change="preview()"
               style="display: none;">
      </div>

      <div v-if="text">
        <div @click="selectFile">{{text}}</div>
        <input type="file"
               accept="image/*"
               :id="id"
               @change="preview()"
               style="display: none;">
      </div>
    </div>

    <van-dialog v-model="showCroper"
                @cancel="cancel"
                @confirm="finish"
                show-cancel-button>
      <div slot="title"
           style="margin-bottom:10px;">
        裁剪图片
      </div>
      <div slot="default"
           style="height:65vh;">
        <vueCropper ref="cropper"
                    :img="img"
                    :outputSize="option.size"
                    :outputType="option.outputType"
                    :info="false"
                    :full="option.full"
                    :canMove="option.canMove"
                    :canMoveBox="option.canMoveBox"
                    :fixedBox="option.fixedBox"
                    :original="option.original"
                    :autoCrop="option.autoCrop"
                    :fixed="option.fixed"
                    :fixedNumber="option.fixedNumber">
        </vueCropper>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import { uploadFile } from '@/service/api/backend'
import { dataURLtoFile } from '@/utils'
export default {
  name: 'imageCroper',
  props: {
    id: {
      type: String,
      default: 'cropperInputId'
    },
    iconWidth: {
      type: String,
      default: '100'
    },
    iconHeight: {
      type: String,
      default: '100'
    },
    text: {
      type: String,
      default: null
    },
    width: {
      type: Number,
      default: 4
    },
    height: {
      type: Number,
      default: 3
    }
  },
  data: function () {
    return {
      img: null,
      showCroper: false,
      option: {
        img: '', // 裁切图片的地址
        outputSize: 0.6, // 裁剪生成图片的质量 0.1-1
        full: true, // 是否输出原图比例的截图
        outputType: 'jpg', // 裁剪生成图片的格式
        canMove: true, // 图片是否允许滚轮缩放
        fixedBox: false, // 固定截图框大小 不允许改变
        original: false, // 上传图片按照原始比例渲染
        canMoveBox: true, // 截图框能否拖动
        // autoCropWidth: 100,
        // autoCropHeight: 100,
        autoCrop: true, // 是否默认生成截图框
        // 开启宽度和高度比例
        fixed: true,
        fixedNumber: [this.width, this.height],
        infoTrue: true,
        centerBox: true, // 截图框限定在图片内
        info: true
      }
    }
  },
  methods: {
    // 触发文件选择
    selectFile () {
      document.getElementById(this.id).click()
    },
    // 取消处理
    cancel () {
      this.showCroper = false
    },
    // 执行上传和返回数据
    finish () {
      this.$refs.cropper.getCropData((data) => {
        let params = {
          name: 'file',
          file: dataURLtoFile('png', 'image/png', data)
        }
        // this.$toast.loading()
        uploadFile(params).then(res => {
          this.$nextTick(() => {
            // this.$toast.clear()
            console.log(res)
            this.$emit('getResult', res.url)
            this.showCroper = false
          })
        }).catch(res => {
          console.log(res)
        })
      })
    },

    preview () {
      let files = document.getElementById(this.id).files[0]
      var imgDataUrl = this.getObjectURL(files)
      this.img = imgDataUrl
      this.showCroper = true
    },
    getObjectURL (file) {
      let url = null
      if (window.createObjectURL !== undefined) { // basic
        url = window.createObjectURL(file)
      } else if (window.webkitURL !== undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file)
      } else if (window.URL !== undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file)
      }
      return url
    },
    dataURLtoFile (fileName, fileType, dataUrl) {
      let arr = dataUrl.split(',')
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], fileName, {
        type: fileType
      })
    }
  }
}
</script>

<style type="text/css" >
.vue-cropper {
  background: black;
  /* background: white; */
  background-image: none !important;
}
.imgCenter {
  justify-content: center;
}
</style>
